<!-- 电影上映时间 -->
<template>
  <div>
    <div class="  text-slate-400 ">【电影上映时间】</div>
    <div ref="target" class="w-full h-full"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";
const props = defineProps({
  data: Array,
});
console.log("LINE>props:", props);
let chart = null;
const target = ref(null);
onMounted(() => {
  chart = echarts.init(target.value);
  ChartInit(); // 将 chart 传递给 ChartInit 函数
});
const ChartInit = () => {
  if (!props.data || props.data.length === 0) {
    console.log("No data to display");
    return;
  }
  const yearCount = props.data.reduce((acc, item) => {
    if (item !== undefined && item !== null) {
      acc[item] = (acc[item] || 0) + 1;
    }
    return acc;
  }, {});

  console.log("Line>yearCount:", yearCount);

  const yAxisData = Object.keys(yearCount).sort();
  const option = {
    xAxis: {
      type: "category",
      data: yAxisData,
      axisLabel: {
        color: "#fff",
      }
    },
    yAxis: {
      type: "value",
      axisLabel: {
        color: "#fff"
      }
    },
    grid: {
      top: 20,
      right: 10,
      bottom: 10,
      left: 0,
      containLabel: true,
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const year = params[0].name;
        const count = yearCount[year];
        return `${year}: ${count}部电影`;
      },
    },
    series: [
      {
        data: Object.values(yearCount),
        type: "line",
        showBackground: true,
        backgroundStyle: {
          color: "rgba(180,180,180,0.2)",
        },
        itemStyle: {
          color: "#5D98CE",
          shadowColor: "rgba(0, 0, 0, 0.3)",
        },
        barWidth: 1,
        // label: {
        //   show: true,
        //   position: "top",
        //   color: "#fff",
        // },
      },
    ],
  };

  // console.log("option:", option); // 检查 option 对象
  try {
    chart.setOption(option);
  } catch (error) {
    console.error("Error setting option:", error);
  }
};

watch(() => props.data, ChartInit);
</script>

<style lang="scss" scoped></style>
